package com.nsgf.library.ui.page;

import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.lifecycle.Observer;

import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.Legend.LegendForm;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.LimitLine.LimitLabelPosition;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IFillFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.LibraryInfo;
import com.nsgf.library.data.bean.WaterDetailInfoBean;
import com.nsgf.library.data.bean.WaterRecordsBean;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.ActivityWaterDetailChartBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.widget.MyMarkerView;
import com.nsgf.library.widget.prckerview.TimePickerView;
import com.nsgf.skjz.utils.Kits;
import com.nsgf.skjz.utils.StringUtil;
import com.nsgf.skjz.utils.ToastUtils;
import com.nsgf.skjz.utils.UnitTo;
import com.nsgf.skjz.utils.Utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 水情
 */
public class WaterDetailActivity extends BaseActivity implements
        OnChartValueSelectedListener {

    WaterDetailStates mState;
    private AccountRequester mAccountRequester;
    protected Typeface tfRegular;
    private ActivityWaterDetailChartBinding mBinding;

    private float axisMaximum = 1f;
    private boolean isLandscape = false;


    @Override
    protected void initViewModel() {

        mState = getActivityScopeViewModel(WaterDetailStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_water_detail_chart, BR.vm, mState)
                .addBindingParam(BR.click, new ClickProxy());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLifecycle().addObserver(mAccountRequester);

        mState.titleBar.set(getIntent().getStringExtra("title"));
        mBinding = (ActivityWaterDetailChartBinding) getBinding();
        tfRegular = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");

        // 设置横屏切换按钮
        if (mBinding.titlebar != null && mBinding.titlebar.titleBarClear != null) {
            mBinding.titlebar.titleBarClear.setVisibility(View.VISIBLE);
            mBinding.titlebar.titleBarClear.setImageResource(R.drawable.ic_nsgf_video_big);
            mBinding.titlebar.titleBarClear.setOnClickListener(view -> {
                if (isLandscape) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                } else {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }
                isLandscape = !isLandscape;
            });
        }

        // startDate 默认今天
        Calendar calendarStar = Calendar.getInstance();
        mState.startDate.set(ymd.format(calendarStar.getTime()));
        mState.startDateSrc.set(ymd.format(calendarStar.getTime()) + "\n08:00");
        starTime = calendarStar;

        // endDate 默认明天
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, 1); // 加1天，即明天
        mState.endDateSrc.set(ymd.format(calendar.getTime()) + "\n08:00");
        mState.endDate.set(ymd.format(calendar.getTime()));
        endTime = calendar;

        UnitTo.setBorder(this, R.color.radio_text_check_color, R.color.radio_text_check_color, R.color.white, mBinding.ivNsgfWorkPMonth, 5);
        UnitTo.setBorder(this, R.color.color_1D2129, R.color.white, R.color.color_1D2129, mBinding.ivNsgfWorkNMonth, 5);

        mBinding.chart1.setNoDataText("暂无相关数据");
        getDatas();
        mAccountRequester.getWaterDetailInfoResult().observe(this, new Observer<ResponseStatus<WaterDetailInfoBean>>() {
            @Override
            public void onChanged(ResponseStatus<WaterDetailInfoBean> responseStatus) {
                getController().dismissLoading();
                if (responseStatus.getResponseCode() == 200) {
                    mState.detailInfoBeanState.set(responseStatus.getData());
                    
                    // 检查数据是否为空
                    if (responseStatus.getData().getWaterRecordsList() == null || 
                        responseStatus.getData().getWaterRecordsList().isEmpty()) {
                        // 数据为空，恢复初始化状态，清空所有数据
                        clearAllData();
                    } else {
                        // 数据不为空，刷新数据
                        refreshData(responseStatus.getData());
                    }

                    initLineDataSet();
                    setData();

                } else {
                    // 请求失败，清空所有数据
                    clearAllData();
                    ToastUtils.showLongToast(responseStatus.getMsg());
                }
            }
        });
    }

    /**
     * 清空所有数据，恢复初始化状态
     */
    private void clearAllData() {
        // 清空数据更新时间
        mState.dataUpdateTime.set("");
        
        // 重置图表数据
        if (mBinding.chart1 != null) {
            mBinding.chart1.clear();
            mBinding.chart1.invalidate();
        }
        
        // 重置轴最大值
        axisMaximum = 0f;
    }

    /**
     * 刷新数据
     */
    private void refreshData(WaterDetailInfoBean data) {
        // 设置数据更新时间 - 获取记录列表中的最后一条时间
        if (data.getWaterRecordsList() != null && !data.getWaterRecordsList().isEmpty()) {
            // 获取最后一条记录的时间
            WaterDetailInfoBean.WaterRecordsListBean lastRecord = 
                data.getWaterRecordsList().get(data.getWaterRecordsList().size() - 1);
            mState.dataUpdateTime.set("数据更新时间: " + lastRecord.getTm());
            mState.realTimeWaterLevel.set(String.valueOf(lastRecord.getRz()));
        }
        
        // 根据 historyWaterRecordsList 获取当日最高和最低水位
        updateTodayWaterLevel(data);
        
        // 设置汛限水位（如果API没有返回，使用默认值68.5）
        if (data.getRealTimeWaterLevel() != null) {
            if (data.getRealTimeWaterLevel().getFloodControlLevel() == 0) {
                data.getRealTimeWaterLevel().setFloodControlLevel(68.5);
            }
        }
    }

    /**
     * 根据 historyWaterRecordsList 计算历史、今年和当日的最高和最低水位
     */
    private void updateTodayWaterLevel(WaterDetailInfoBean data) {
        // 获取当前日期和年份
        Calendar today = Calendar.getInstance();
        String todayStr = ymd.format(today.getTime()); // yyyy-MM-dd 格式
        int currentYear = today.get(Calendar.YEAR);
        
        // 历史最高/最低（所有数据）
        WaterDetailInfoBean.HistoryWaterRecordsListBean historyMaxRecord = null;
        WaterDetailInfoBean.HistoryWaterRecordsListBean historyMinRecord = null;
        double historyMaxRz = Double.MIN_VALUE;
        double historyMinRz = Double.MAX_VALUE;
        
        // 今年最高/最低（当前年份的数据）
        WaterDetailInfoBean.HistoryWaterRecordsListBean yearMaxRecord = null;
        WaterDetailInfoBean.HistoryWaterRecordsListBean yearMinRecord = null;
        double yearMaxRz = Double.MIN_VALUE;
        double yearMinRz = Double.MAX_VALUE;
        
        // 当日最高/最低
        WaterDetailInfoBean.HistoryWaterRecordsListBean dayMaxRecord = null;
        WaterDetailInfoBean.HistoryWaterRecordsListBean dayMinRecord = null;
        double dayMaxRz = Double.MIN_VALUE;
        double dayMinRz = Double.MAX_VALUE;
        
        // 遍历 historyWaterRecordsList
        if (data.getHistoryWaterRecordsList() != null) {
            for (WaterDetailInfoBean.HistoryWaterRecordsListBean record : data.getHistoryWaterRecordsList()) {
                if (record.getTm() == null || record.getRz() == null) {
                    continue;
                }
                
                double rz = record.getRz();
                
                // 提取日期和年份
                String recordDate = record.getTm().substring(0, 10); // 提取 yyyy-MM-dd
                int recordYear = 0;
                try {
                    recordYear = Integer.parseInt(record.getTm().substring(0, 4)); // 提取年份
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                
                // 1. 计算历史最高/最低（所有数据）
                if (rz > historyMaxRz) {
                    historyMaxRz = rz;
                    historyMaxRecord = record;
                }
                if (rz < historyMinRz) {
                    historyMinRz = rz;
                    historyMinRecord = record;
                }
                
                // 2. 计算今年最高/最低（当前年份的数据）
                if (recordYear == currentYear) {
                    if (rz > yearMaxRz) {
                        yearMaxRz = rz;
                        yearMaxRecord = record;
                    }
                    if (rz < yearMinRz) {
                        yearMinRz = rz;
                        yearMinRecord = record;
                    }
                }
                
                // 3. 计算当日最高/最低
                if (recordDate.equals(todayStr)) {
                    if (rz > dayMaxRz) {
                        dayMaxRz = rz;
                        dayMaxRecord = record;
                    }
                    if (rz < dayMinRz) {
                        dayMinRz = rz;
                        dayMinRecord = record;
                    }
                }
            }
        }
        
        // 设置历史最高水位
        if (historyMaxRecord != null) {
            WaterDetailInfoBean.MaxHisWaterLevelBean maxBean = new WaterDetailInfoBean.MaxHisWaterLevelBean();
            maxBean.setId(historyMaxRecord.getId());
            maxBean.setFacilityCode(historyMaxRecord.getFacilityCode());
            maxBean.setTm(historyMaxRecord.getTm());
            maxBean.setRz(historyMaxRecord.getRz());
            data.setMaxHisWaterLevel(maxBean);
        }
        
        // 设置历史最低水位
        if (historyMinRecord != null) {
            WaterDetailInfoBean.MinHisWaterLevelBean minBean = new WaterDetailInfoBean.MinHisWaterLevelBean();
            minBean.setId(historyMinRecord.getId());
            minBean.setFacilityCode(historyMinRecord.getFacilityCode());
            minBean.setTm(historyMinRecord.getTm());
            minBean.setRz(historyMinRecord.getRz());
            data.setMinHisWaterLevel(minBean);
        }
        
        // 设置今年最高水位
        if (yearMaxRecord != null) {
            WaterDetailInfoBean.MaxHisWaterLevelYearBean maxBean = new WaterDetailInfoBean.MaxHisWaterLevelYearBean();
            maxBean.setId(yearMaxRecord.getId());
            maxBean.setFacilityCode(yearMaxRecord.getFacilityCode());
            maxBean.setTm(yearMaxRecord.getTm());
            maxBean.setRz(yearMaxRecord.getRz());
            data.setMaxHisWaterLevelYear(maxBean);
        }
        
        // 设置今年最低水位
        if (yearMinRecord != null) {
            WaterDetailInfoBean.MinHisWaterLevelYearBean minBean = new WaterDetailInfoBean.MinHisWaterLevelYearBean();
            minBean.setId(yearMinRecord.getId());
            minBean.setFacilityCode(yearMinRecord.getFacilityCode());
            minBean.setTm(yearMinRecord.getTm());
            minBean.setRz(yearMinRecord.getRz());
            data.setMinHisWaterLevelYear(minBean);
        }
        
        // 设置当日最高水位
        if (dayMaxRecord != null) {
            WaterDetailInfoBean.MaxHisWaterLevelDayBean maxBean = new WaterDetailInfoBean.MaxHisWaterLevelDayBean();
            maxBean.setId((long) dayMaxRecord.getId()); // Day类型的id是long，需要转换
            maxBean.setFacilityCode(dayMaxRecord.getFacilityCode());
            maxBean.setTm(dayMaxRecord.getTm());
            maxBean.setRz(dayMaxRecord.getRz());
            data.setMaxHisWaterLevelDay(maxBean);
        }
        
        // 设置当日最低水位
        if (dayMinRecord != null) {
            WaterDetailInfoBean.MinHisWaterLevelDayBean minBean = new WaterDetailInfoBean.MinHisWaterLevelDayBean();
            minBean.setId((long) dayMinRecord.getId()); // Day类型的id是long，需要转换
            minBean.setFacilityCode(dayMinRecord.getFacilityCode());
            minBean.setTm(dayMinRecord.getTm());
            minBean.setRz(dayMinRecord.getRz());
            data.setMinHisWaterLevelDay(minBean);
        }
    }

    /**
     * 数据加载
     */
    private void setData() {
        // 检查数据是否为空
        if (mState.detailInfoBeanState.get() == null || 
            mState.detailInfoBeanState.get().getWaterRecordsList() == null ||
            mState.detailInfoBeanState.get().getWaterRecordsList().isEmpty()) {
            // 数据为空，清空图表并设置默认范围
            mBinding.chart1.clear();
            mBinding.chart1.getAxisLeft().setAxisMaximum(10f);
            mBinding.chart1.getAxisLeft().setAxisMinimum(0f);
            mBinding.chart1.invalidate();
            return;
        }

        List<Entry> entries = new ArrayList<>();
        List<WaterDetailInfoBean.WaterRecordsListBean> waterRecordsList = 
            mState.detailInfoBeanState.get().getWaterRecordsList();

        // 收集有效数据
        for (int i = 0; i < waterRecordsList.size(); i++) {
            WaterDetailInfoBean.WaterRecordsListBean data = waterRecordsList.get(i);
            if (data != null) {
                double rzValueDouble = data.getRz();
                // 检查数据是否有效（不是 NaN 或 Infinity）
                if (!Double.isNaN(rzValueDouble) && !Double.isInfinite(rzValueDouble)) {
                    float rzValue = (float) rzValueDouble;
                    Entry entry = new Entry(i, rzValue);
                    entries.add(entry);
                }
            }
        }

        // 如果没有有效数据，清空图表
        if (entries.isEmpty()) {
            mBinding.chart1.clear();
            mBinding.chart1.getAxisLeft().setAxisMaximum(10f);
            mBinding.chart1.getAxisLeft().setAxisMinimum(0f);
            mBinding.chart1.invalidate();
            return;
        }

        // 每一个LineDataSet代表一条线
        LineDataSet lineDataSet = new LineDataSet(entries, "");
        lineDataSet.setColor(getResources().getColor(R.color.color_00EAFF));
        lineDataSet.setCircleColor(getResources().getColor(R.color.color_00EAFF));
        lineDataSet.setLineWidth(1f);
        lineDataSet.setCircleRadius(1f);
        lineDataSet.setDrawCircles(false);
        lineDataSet.setDrawValues(false);
        //设置曲线值的圆点是实心还是空心
        lineDataSet.setDrawCircleHole(false);
        lineDataSet.setValueTextSize(10f);
        lineDataSet.enableDashedHighlightLine(10f, 5f, 0f);
        //设置折线图填充
        lineDataSet.setDrawFilled(true);
        lineDataSet.setFormLineWidth(0f);
        lineDataSet.setFormSize(15.f);
        //设置曲线展示为圆滑曲线（如果不设置则默认折线）
        lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);

        lineDataSet.setFillFormatter(new IFillFormatter() {
            @Override
            public float getFillLinePosition(ILineDataSet dataSet, LineDataProvider dataProvider) {
                return mBinding.chart1.getAxisLeft().getAxisMinimum();
            }
        });
        LineData lineData = new LineData(lineDataSet);
        mBinding.chart1.setData(lineData);

        float max, min;
        
        // 获取数据的最大值和最小值
        float yMax = lineData.getYMax();
        float yMin = lineData.getYMin();
        
        // 检查数据是否有效
        if (Float.isNaN(yMax) || Float.isInfinite(yMax) || 
            Float.isNaN(yMin) || Float.isInfinite(yMin)) {
            // 数据异常，设置默认范围
            max = 10f;
            min = 0f;
        } else {
            //序列化float值比较
            final float EPSILON = 1e-6f;
            final boolean sameData = Math.abs(yMax - yMin) < EPSILON;
            
            if(sameData) {
                // 处理只有一条数据或所有数据值相同的情况
                float singleValue = yMax;
                if (singleValue == 0f) {
                    // 如果值为0，设置一个默认范围
                    max = 10f;
                    min = 0f;
                } else {
                    // 如果值不为0，设置一个合适的范围
                    float range = Math.abs(singleValue) * 0.2f; // 上下各20%的范围
                    max = singleValue + range;
                    min = singleValue - range;
                    // 确保最小值不为负
                    if (min < 0) {
                        min = 0;
                    }
                }
            } else {
                // 正常情况，设置上下扩展范围
                float range = (yMax - yMin) / 3;
                max = yMax + range;
                min = yMin - range;
                // 确保最小值不为负
                if (min < 0) {
                    min = 0;
                }
                // 限制最大值，避免显示异常大的数值
                if (max > 10000f) {
                    max = 10000f;
                }
            }
        }

        mBinding.chart1.getAxisLeft().setAxisMaximum(max);
        mBinding.chart1.getAxisLeft().setAxisMinimum(min);
        mBinding.chart1.invalidate();
    }

    /**
     * 曲线初始化设置 一个LineDataSet 代表一条曲线
     */
    private void initLineDataSet() {

        {   // // Chart Style // //

            // background color
            mBinding.chart1.setBackgroundColor(Color.WHITE);

            //是否展示网格线
            mBinding.chart1.setDrawGridBackground(false);
            //是否显示边界
            mBinding.chart1.setDrawBorders(false);
            // disable description text
            mBinding.chart1.getDescription().setEnabled(false);

            // enable touch gestures
            mBinding.chart1.setTouchEnabled(true);

            // set listeners
            mBinding.chart1.setOnChartValueSelectedListener(this);


            // enable scaling and dragging
            mBinding.chart1.setDragEnabled(true);
            mBinding.chart1.setScaleEnabled(true);
            // mBinding.chart1.setScaleXEnabled(true);
            // mBinding.chart1.setScaleYEnabled(true);

            // force pinch zoom along both axis
            mBinding.chart1.setPinchZoom(true);
        }

        XAxis xAxis;
        {   // // X-Axis Style // //
            xAxis = mBinding.chart1.getXAxis();

            xAxis.setDrawGridLines(false);
            xAxis.setGranularity(1f);
            // vertical grid lines
            xAxis.enableGridDashedLine(10f, 10f, 0f);

            xAxis.setLabelRotationAngle(-30f);
            xAxis.setValueFormatter(new ValueFormatter() {
                @Override
                public String getAxisLabel(float value, AxisBase axis) {
                    if (mState.detailInfoBeanState.get().getWaterRecordsList().size() == 0 || value < 0)
                        return "";
                    if ((int) value >= mState.detailInfoBeanState.get().getWaterRecordsList().size())
                        return "";
                    String tradeDate = mState.detailInfoBeanState.get().getWaterRecordsList().get((int) value).getTm();
                    return Utils.formatTime(tradeDate);
                }
            });
        }

        // 根据横竖屏状态设置不同的偏移量
        boolean isLandscapeMode = getResources().getConfiguration().orientation == android.content.res.Configuration.ORIENTATION_LANDSCAPE;
        if (isLandscapeMode) {
            // 横屏时增加偏移量，确保XY轴标签完全显示
            mBinding.chart1.setExtraBottomOffset(40f); // X轴标签旋转后需要更多空间
            mBinding.chart1.setExtraLeftOffset(30f); // Y轴标签需要更多空间
            mBinding.chart1.setExtraRightOffset(10f); // 右侧也需要一些空间
        } else {
            // 竖屏时的偏移量
            mBinding.chart1.setExtraBottomOffset(10f);
            mBinding.chart1.setExtraLeftOffset(10f);
            mBinding.chart1.setExtraRightOffset(0f);
        }
        
        // 根据数据数量动态设置X轴标签数量，小于8用实际数量，大于等于8设置8
        int xLabelCount = 8;
        if (mState.detailInfoBeanState.get() != null && 
            mState.detailInfoBeanState.get().getWaterRecordsList() != null) {
            int dataSize = mState.detailInfoBeanState.get().getWaterRecordsList().size();
            xLabelCount = dataSize < 8 ? dataSize : 8;
        }
        xAxis.setLabelCount(Math.max(xLabelCount, 1), true); // 至少显示1个标签
        
        YAxis yAxis;
        {   // // Y-Axis Style // //
            yAxis = mBinding.chart1.getAxisLeft();

            yAxis.setTypeface(tfRegular);
            
            // 根据数据数量动态设置Y轴标签数量
            int yLabelCount = 8;
            if (mState.detailInfoBeanState.get() != null && 
                mState.detailInfoBeanState.get().getWaterRecordsList() != null) {
                int dataSize = mState.detailInfoBeanState.get().getWaterRecordsList().size();
                yLabelCount = dataSize < 8 ? dataSize : 8;
            }
            yAxis.setLabelCount(Math.max(yLabelCount, 1), true); // 至少显示1个标签
            
            // 设置Y轴标签位置在图表外部，避免数值显示不全
            yAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
            
            // 设置顶部空间
            yAxis.setSpaceTop(15f);
            
            // 确保最小值从0开始
            yAxis.setAxisMinimum(0f);
            
            // 绘制虚线网格
            yAxis.enableGridDashedLine(10f, 10f, 0f);
            
            // 设置Y轴数值格式，保留两位小数
            yAxis.setValueFormatter(new ValueFormatter() {
                @Override
                public String getAxisLabel(float value, AxisBase axis) {
                    return String.format(Locale.getDefault(), "%.2f", value);
                }
            });
            
            // disable dual axis (only use LEFT axis)
            mBinding.chart1.getAxisRight().setEnabled(false);

        }

        // create marker to display box when values are selected

        MyMarkerView mv = new MyMarkerView(this, xAxis.getValueFormatter(), yAxis.getValueFormatter(), "水位", "#00EAFF", mState.detailInfoBeanState.get().getWaterRecordsList());
        mv.setChartView(mBinding.chart1);
        mBinding.chart1.setMarker(mv);
        mBinding.chart1.invalidate();

        {   // // Create Limit Lines // //
            LimitLine llXAxis = new LimitLine(9f, "Index 10");
            llXAxis.setLineWidth(1f);
            llXAxis.enableDashedLine(10f, 10f, 0f);
            llXAxis.setLabelPosition(LimitLabelPosition.RIGHT_BOTTOM);
            llXAxis.setTextSize(10f);
            llXAxis.setTypeface(tfRegular);
            // draw limit lines behind data instead of on top
            yAxis.setDrawLimitLinesBehindData(true);
            xAxis.setDrawLimitLinesBehindData(true);

            //xAxis.addLimitLine(llXAxis);
        }

        //X轴设置显示位置在底部
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);


        // draw points over time
        mBinding.chart1.animateX(1500);
        mBinding.chart1.animateY(1500);

        // get the legend (only possible after setting data)
        Legend l = mBinding.chart1.getLegend();
        //显示位置 左下方
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        // draw legend entries as lines
        l.setForm(LegendForm.LINE);
        l.setEnabled(false);
        while (!mBinding.chart1.isFullyZoomedOut()) {

            mBinding.chart1.zoomOut();
        }
    }

    private void getDatas() {
            mState.trafficTitle.set("水位情况");
            
            // 获取传递的参数
            String facilityCode = getIntent().getStringExtra("facilityCode");
            String projectCode = getIntent().getStringExtra("projectCode");
            String facilityType = getIntent().getStringExtra("facilityType");
            
            // 格式化时间为 "yyyy-MM-dd HH:mm:ss" 格式
            String startTime = mState.startDate.get() + " 08:00:00";
            String endTime = mState.endDate.get() + " 08:00:00";
            
            // 如果 projectCode 或 facilityType 为空，使用默认值
            if (projectCode == null) {
                projectCode = "";
            }
            if (facilityType == null) {
                facilityType = "water.obj.type.8";  // 默认值
            }
            
            // 使用新的接口方法
            mAccountRequester.getWaterDiagram(
                    startTime,
                    endTime,
                    projectCode,
                    facilityCode,
                    facilityType);

    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {
        Log.i("Entry selected", e.toString());
        Log.i("LOW HIGH", "low: " + mBinding.chart1.getLowestVisibleX() + ", high: " + mBinding.chart1.getHighestVisibleX());
        Log.i("MIN MAX", "xMin: " + mBinding.chart1.getXChartMin() + ", xMax: " + mBinding.chart1.getXChartMax() + ", yMin: " + mBinding.chart1.getYChartMin() + ", yMax: " + mBinding.chart1.getYChartMax());
    }

    @Override
    public void onNothingSelected() {
        Log.i("Nothing selected", "Nothing selected.");
        // 点击空白区域时，清除高亮，隐藏marker
        mBinding.chart1.highlightValue(null);
    }

    @Override
    public void onBackPressed() {
        int orientation = getRequestedOrientation();
        if (orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            // Activity 设置为横屏，先切换回竖屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            isLandscape = false;
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onClickSecurity(View v) {
        super.onClickSecurity(v);
        if (v.getId() == R.id.title_bar_back) {
            int orientation = getRequestedOrientation();
            if (orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                // Activity 设置为横屏，先切换回竖屏
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                isLandscape = false;
            } else {
                finish();
            }
        }
    }

    @Override
    public void onConfigurationChanged(android.content.res.Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // 更新横屏状态
        isLandscape = (newConfig.orientation == android.content.res.Configuration.ORIENTATION_LANDSCAPE);
        // 横竖屏切换时，重新初始化图表以确保正确显示
        if (mBinding != null && mBinding.chart1 != null && mState.detailInfoBeanState.get() != null) {
            // 延迟一下，确保布局已经完成
            mBinding.chart1.post(() -> {
                initLineDataSet();
                setData();
            });
        }
    }

    private Calendar starTime, endTime;

    private static SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

    public static class WaterDetailStates extends StateHolder {

        public final State<WaterDetailInfoBean> detailInfoBeanState = new State<>(new WaterDetailInfoBean());
        public final State<String> dataUpdateTime = new State<>("");
        public final State<String> realTimeWaterLevel = new State<>("");
        public final State<String> trafficTitle = new State<>("");

    }

    public class ClickProxy {

        public void pMonth() {

            starTime.set(Calendar.DAY_OF_MONTH, starTime.get(Calendar.DAY_OF_MONTH) - 1);
            mState.startDate.set(Kits.Date.getYmd(starTime.getTimeInMillis()));
            mState.startDateSrc.set(Kits.Date.getYmd(starTime.getTimeInMillis()) + "\n08:00");


            endTime.setTime(starTime.getTime());
            endTime.set(Calendar.DAY_OF_MONTH, endTime.get(Calendar.DAY_OF_MONTH) + 1);
            mState.endDate.set(Kits.Date.getYmd(endTime.getTimeInMillis()));
            mState.endDateSrc.set(Kits.Date.getYmd(endTime.getTimeInMillis()) + "\n08:00");

            getController().displayLoading();
            getDatas();

        }

        public void nMonth() {

            endTime.set(Calendar.DAY_OF_MONTH, endTime.get(Calendar.DAY_OF_MONTH) + 1);
            mState.endDate.set(Kits.Date.getYmd(endTime.getTimeInMillis()));
            mState.endDateSrc.set(Kits.Date.getYmd(endTime.getTimeInMillis()) + "\n08:00");

            starTime.setTime(endTime.getTime());
            starTime.set(Calendar.DAY_OF_MONTH, starTime.get(Calendar.DAY_OF_MONTH) - 1);
            mState.startDate.set(Kits.Date.getYmd(starTime.getTimeInMillis()));
            mState.startDateSrc.set(Kits.Date.getYmd(starTime.getTimeInMillis()) + "\n08:00");

            getController().displayLoading();
            getDatas();
        }


        public void screenStarTime() {

            boolean[] type = new boolean[]{true, true, true, false, false, false};//显示类型 默认全部显示

            TimePickerView mTimePickerView = new TimePickerView.Builder(WaterDetailActivity.this, new TimePickerView.OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    mState.startDate.set(ymd.format(date));
                    mState.startDateSrc.set(ymd.format(date) + "\n08:00");

                    getDatas();
                    starTime.setTime(date);
                }
            }).isCyclic(false)
                    .setRangDate(null, null)
                    .setType(type)
                    .setTitleText("开始日期")
                    .setDate(starTime).build();

            mTimePickerView.show();


        }

        public void screenEndTime() {

            boolean[] type = new boolean[]{true, true, true, false, false, false};//显示类型 默认全部显示

            TimePickerView mTimePickerView = new TimePickerView.Builder(WaterDetailActivity.this, new TimePickerView.OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    mState.endDate.set(ymd.format(date));
                    mState.endDateSrc.set(ymd.format(date) + "\n08:00");
                    getDatas();
                    endTime.setTime(date);
                }
            }).isCyclic(false)
                    .setRangDate(null, null)
                    .setType(type)
                    .setTitleText("结束日期")
                    .setDate(endTime).build();

            mTimePickerView.show();


        }

    }
}
